<script setup lang="ts">
defineOptions({
  name: "checkListItem"
});
import { ref, reactive, computed, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { PxMessage } from "px-ui";
import { saveAcidDrumExecution, submitAcidDrumExecution } from "@/api/modules/operation";
import sop from "./sop.vue";
import upload from "./upload.vue";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import { cloneDeep } from "@pureadmin/utils";

const route = useRoute();
const router = useRouter();

const addArguments: Record<string, any> = {
  // 任务类型(1：气瓶， 2：酸桶)
  taskType: 2
};

interface Props {
  data: Record<string, any>;
  disabled?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  data: () => ({ data: null, title: "" }),
  disabled: false
});

const isNotEdit = ref<boolean>(true);
const isShowEditBtn = ref<boolean>(false);

const sopRef = ref<InstanceType<typeof sop> | null>(null);
const uploadRef = ref<InstanceType<typeof upload> | null>(null);
const collapseValue = defineModel({ type: String, default: "" });
const uploadData = ref<{ imgList: Array<any>; fileList: Array<any>; executeRemark: string }>({
  imgList: [],
  fileList: [],
  executeRemark: ""
});

const extraFormRef = ref<FormInstance>(null);
const extraForm = ref<{ operator: string; confirmor: string }>({
  operator: "",
  confirmor: ""
});
const extraFormRules = reactive<FormRules<{ operator: string; confirmor: string }>>({
  operator: [{ required: true, message: "请输入换瓶操作人", trigger: ["blur"] }],
  confirmor: [{ required: true, message: "请输入换瓶确认人", trigger: ["blur"] }]
});

const realDisabled = computed(() => props.disabled || isNotEdit.value);

const validate = async () => {
  await extraFormRef.value.validate();
  await sopRef.value.validate();
  await uploadRef.value.validate();
};

const getParams = () => {
  const { id = "" } = props.data;
  const { operator = "", confirmor = "" } = extraForm.value;
  let taskChecklistResult = cloneDeep(sopRef.value.list);
  taskChecklistResult = taskChecklistResult.map(item => {
    delete item.status;
    return item;
  });
  let fileIdList = [];
  let imgIdList = [];
  const { imgList = [], fileList = [], executeRemark = "" } = uploadData.value;
  fileList?.length && (fileIdList = fileList.map(item => item.id));
  imgList?.length && (imgIdList = imgList.map(item => item.id));
  return { id, operator, confirmor, taskChecklistResult, imgIdList, fileIdList, executeRemark };
};

const editHandler = () => {
  isNotEdit.value = false;
  isShowEditBtn.value = false;
};

const submitHandler = useThrottleFn(async () => {
  await validate();
  const subTaskDTO = getParams();
  const { taskType } = addArguments;
  const {
    query: { id = "" }
  } = route;
  const params = { id, taskType, subTaskDTO };
  await submitAcidDrumExecution(params);
  isShowEditBtn.value = true;
  isNotEdit.value = true;
  const userInfo = localStorage.getItem("userInfo");
  const { userId = null } = JSON.parse(userInfo);
  // eslint-disable-next-line
  userId && (props.data.executor = userId);
  PxMessage.success("提交成功！");
  if (props.data.isLast) {
    const path = "/gas/operation/acidDrumManage/replaceAcidDrum";
    router.push({ path });
  }
}, delay);

const saveHandler = useThrottleFn(async () => {
  const subTaskDTO = getParams();
  const { taskType } = addArguments;
  const {
    query: { id = "" }
  } = route;
  const params = { id, taskType, subTaskDTO };
  await saveAcidDrumExecution(params);
  PxMessage.success("保存成功！");
}, delay);

const init = () => {
  const { operator = "", confirmor = "", imgList = [], fileList = [], executeRemark = "" } = props.data;
  extraForm.value.operator = operator;
  extraForm.value.confirmor = confirmor;
  uploadData.value.imgList = imgList;
  uploadData.value.fileList = fileList;
  uploadData.value.executeRemark = executeRemark;
  uploadRef.value.init();
};

watch(
  () => props.data,
  val => {
    if (val) {
      const { executor = "", subTaskTypeDesc = "", isLastExecutor = false, firstEmptyTitle = "", isLast = false } = val;
      if (props.disabled) {
        isShowEditBtn.value = false;
        isNotEdit.value = true;
      } else if (!!executor) {
        if (isLastExecutor) {
          const userInfo = localStorage.getItem("userInfo");
          const { userId = null } = JSON.parse(userInfo);
          if (userId === executor) {
            isShowEditBtn.value = true;
            isNotEdit.value = true;
          } else {
            isShowEditBtn.value = false;
            isNotEdit.value = true;
          }
          if (isLast) {
            isShowEditBtn.value = false;
          }
        } else {
          isShowEditBtn.value = false;
          isNotEdit.value = true;
        }
      } else {
        if (subTaskTypeDesc === firstEmptyTitle) {
          // 当前需要填入的项
          isShowEditBtn.value = false;
          isNotEdit.value = false;
        } else {
          // 在当前需要填入项后面的项
          isShowEditBtn.value = false;
          // 目前暂时放开
          isNotEdit.value = false;
        }
      }
    }
  },
  {
    immediate: true,
    once: true
  }
);

onMounted(() => {
  init();
});

defineExpose({
  init,
  validate,
  getParams
});
</script>

<template>
  <div>
    <div class="collapse-content-form">
      <px-form
        ref="extraFormRef"
        inline
        label-width="120px"
        :model="extraForm"
        :rules="extraFormRules"
        :disabled="realDisabled"
        scroll-to-error
        :scroll-into-view-options="{ behavior: 'smooth' }"
      >
        <px-row :gutter="32">
          <px-col :span="8">
            <px-form-item label="换桶操作人" prop="operator">
              <px-input v-model.trim="extraForm.operator" clearable placeholder="请输入换桶操作人" />
            </px-form-item>
          </px-col>
          <px-col :span="8">
            <px-form-item label="换桶确认人" prop="confirmor">
              <px-input v-model.trim="extraForm.confirmor" clearable placeholder="请输入换桶确认人" />
            </px-form-item>
          </px-col>
        </px-row>
      </px-form>
    </div>
    <sop ref="sopRef" :disabled="realDisabled" :data="data?.data" :title="data?.title" />
    <upload ref="uploadRef" v-model="uploadData" :disabled="realDisabled" />
    <!-- <div class="btns">
      <px-button v-if="isShowEditBtn" type="primary" plain @click="editHandler">再次编辑</px-button>
      <px-button v-if="!realDisabled" type="primary" @click="submitHandler">提交</px-button>
      <px-button v-if="!realDisabled" type="primary" plain @click="saveHandler">保存为草稿</px-button>
    </div> -->
  </div>
</template>

<style lang="scss" scoped>
.px-collapse {
  overflow: hidden;
  border-right: 1px solid var(--px-collapse-border-color);
  border-left: 1px solid var(--px-collapse-border-color);
  border-radius: 6px;

  :deep(.px-collapse-item) {
    > div {
      padding: 0 16px;

      &:nth-child(1) {
        background-color: rgb(248 248 248);
        border-bottom: 1px solid var(--px-collapse-border-color);

        .px-collapse-item__header {
          background-color: rgb(248 248 248);
          border-bottom: none;
        }
      }

      &:nth-child(2) {
        padding: 16px;
      }
    }

    .px-collapse-item__content {
      padding-bottom: 0;

      .collapse-content {
        .collapse-content-form {
          .px-input {
            // width: 400px;
          }
        }
      }
    }
  }
}

.btns {
  display: flex;
  align-items: center;
}
</style>
